import { Translation, TranslationModule, TranslationInfo } from '../types/translation';
import { ForexDanaModuleTransformer, ModuleTransformResult } from './ForexDanaModuleTransformer';
import { ModuleReferenceHandler } from './ModuleReferenceHandler';
import { ClassifierInterface, ClassificationResult, ClassifierConfig } from './ClassifierInterface';

/**
 * ForexDana项目的翻译分类结果
 */
export interface ForexDanaClassificationResult extends ClassificationResult {
  // 基础设施类翻译
  infrastructureTranslations: {
    // 按基础设施的一级目录分组
    [directory: string]: Translation[];
  };
  
  // 业务功能类翻译（来自UI目录）
  businessTranslations: {
    // 按UI目录下的一级子目录分组
    [subModule: string]: Translation[];
  };
  
  // 未分类的翻译
  unclassifiedTranslations: Translation[];
  
  // 统计信息
  statistics: {
    totalCount: number;
    infrastructureCount: number;
    businessCount: number;
    unclassifiedCount: number;
    
    infrastructureBreakdown: {
      [directory: string]: number;
    };
    
    businessBreakdown: {
      [subModule: string]: number;
    };
  };
}

/**
 * ForexDana项目专用的翻译分类器
 * 根据文件路径将翻译分为基础设施类和业务功能类
 */
export class ForexDanaClassifier implements ClassifierInterface {
  readonly type = 'forexdana';
  
  private readonly infrastructureDirs: string[];
  private moduleTransformer: ForexDanaModuleTransformer;
  private referenceHandler: ModuleReferenceHandler;
  
  constructor(config?: ClassifierConfig) {
    // 使用配置或默认值初始化
    this.infrastructureDirs = config?.rules?.infrastructureDirs || [
      'adapter', 'app', 'base', 'dao', 'entity', 
      'http', 'mvp', 'receiver', 'socket', 'utils', 'widget'
    ];
    
    this.moduleTransformer = new ForexDanaModuleTransformer();
    this.referenceHandler = new ModuleReferenceHandler();
  }
  
  /**
   * 对翻译数组进行分类
   * @param translations 翻译数组
   * @returns 分类结果
   */
  public classify(translations: Translation[] | TranslationInfo[]): ForexDanaClassificationResult {
    const result: ForexDanaClassificationResult = {
      infrastructureTranslations: {},
      businessTranslations: {},
      unclassifiedTranslations: [],
      statistics: {
        totalCount: translations.length,
        infrastructureCount: 0,
        businessCount: 0,
        unclassifiedCount: 0,
        infrastructureBreakdown: {},
        businessBreakdown: {}
      }
    };
    
    // 初始化基础设施目录
    this.infrastructureDirs.forEach(dir => {
      result.infrastructureTranslations[dir] = [];
      result.statistics.infrastructureBreakdown[dir] = 0;
    });
    
    // 处理每个翻译条目
    translations.forEach(translation => {
      // 判断translation是否为TranslationInfo类型
      if ('file' in translation) {
        // TranslationInfo类型
        // 提取精简路径
        const simplifiedPath = this.extractSimplifiedPath(translation.file);
        if (!simplifiedPath) {
          result.unclassifiedTranslations.push(translation as unknown as Translation);
          result.statistics.unclassifiedCount++;
          return;
        }
        
        // 获取第一级目录
        const firstLevelDir = this.getFirstLevelDirectory(simplifiedPath);
        
        // 处理基础设施类
        if (this.infrastructureDirs.includes(firstLevelDir)) {
          if (!result.infrastructureTranslations[firstLevelDir]) {
            result.infrastructureTranslations[firstLevelDir] = [];
            result.statistics.infrastructureBreakdown[firstLevelDir] = 0;
          }
          
          result.infrastructureTranslations[firstLevelDir].push(translation as unknown as Translation);
          result.statistics.infrastructureCount++;
          result.statistics.infrastructureBreakdown[firstLevelDir]++;
          return;
        }
        
        // 处理业务功能类（UI目录）
        if (firstLevelDir === 'ui') {
          // 获取UI下的子模块
          const subModule = this.getSecondLevelDirectory(simplifiedPath) || 'common';
          
          if (!result.businessTranslations[subModule]) {
            result.businessTranslations[subModule] = [];
            result.statistics.businessBreakdown[subModule] = 0;
          }
          
          result.businessTranslations[subModule].push(translation as unknown as Translation);
          result.statistics.businessCount++;
          result.statistics.businessBreakdown[subModule]++;
          return;
        }
        
        // 无法分类的情况
        result.unclassifiedTranslations.push(translation as unknown as Translation);
        result.statistics.unclassifiedCount++;
      } else {
        // Translation类型，直接处理
        result.unclassifiedTranslations.push(translation as Translation);
        result.statistics.unclassifiedCount++;
      }
    });
    
    return result;
  }
  
  /**
   * 从完整路径中提取精简路径
   * @param filePath 完整文件路径
   * @returns 精简路径，如'widget/ViewFindAllView.kt'
   */
  public extractSimplifiedPath(filePath: string): string | null {
    if (!filePath) return null;
    
    // 使用正则表达式提取关键路径部分
    // 查找com/indone/online/之后的所有内容
    const match = filePath.match(/com\/indone\/online\/(.+)/);
    if (match && match[1]) {
      return match[1];
    }
    
    // 如果上面的匹配失败，尝试直接从java或kotlin目录后开始提取
    const fallbackMatch = filePath.match(/\/(java|kotlin)\/(.+)/);
    if (fallbackMatch && fallbackMatch[2]) {
      // 如果路径包含com/indone/online，则从这之后开始
      const parts = fallbackMatch[2].split('com/indone/online/');
      if (parts.length > 1) {
        return parts[1];
      }
      return fallbackMatch[2];
    }
    
    return null;
  }
  
  /**
   * 获取路径的第一级目录
   * @param path 路径字符串
   * @returns 第一级目录名
   */
  private getFirstLevelDirectory(path: string): string {
    if (!path) return '';
    
    const parts = path.split('/');
    return parts[0] || '';
  }
  
  /**
   * 获取路径的第二级目录
   * @param path 路径字符串
   * @returns 第二级目录名，如果不存在则返回null
   */
  private getSecondLevelDirectory(path: string): string | null {
    if (!path) return null;
    
    const parts = path.split('/');
    if (parts.length >= 2) {
      return parts[1];
    }
    
    return null;
  }
  
  /**
   * 生成分类报告
   * @param result 分类结果
   * @returns 格式化的报告字符串
   */
  public generateReport(result: ForexDanaClassificationResult): string {
    // 对业务模块和基础设施模块按数量排序
    const sortedInfrastructure = Object.entries(result.statistics.infrastructureBreakdown)
      .sort((a, b) => b[1] - a[1]);
      
    const sortedBusiness = Object.entries(result.statistics.businessBreakdown)
      .sort((a, b) => b[1] - a[1]);
    
    // 构建报告
    let report = '==== ForexDana翻译分类报告 ====\n\n';
    
    report += `总翻译条目: ${result.statistics.totalCount}\n`;
    report += `基础设施类: ${result.statistics.infrastructureCount} (${this.percentage(result.statistics.infrastructureCount, result.statistics.totalCount)}%)\n`;
    report += `业务功能类: ${result.statistics.businessCount} (${this.percentage(result.statistics.businessCount, result.statistics.totalCount)}%)\n`;
    report += `未分类条目: ${result.statistics.unclassifiedCount} (${this.percentage(result.statistics.unclassifiedCount, result.statistics.totalCount)}%)\n\n`;
    
    // 基础设施类明细
    report += '=== 基础设施类明细 ===\n';
    sortedInfrastructure.forEach(([dir, count]) => {
      if (count > 0) {
        report += `${dir}: ${count} (${this.percentage(count, result.statistics.infrastructureCount)}%)\n`;
      }
    });
    
    // 业务功能类明细
    report += '\n=== 业务功能类明细 ===\n';
    sortedBusiness.forEach(([module, count]) => {
      if (count > 0) {
        report += `${module}: ${count} (${this.percentage(count, result.statistics.businessCount)}%)\n`;
      }
    });
    
    return report;
  }
  
  /**
   * 计算百分比
   * @param part 部分数量
   * @param total 总数量
   * @returns 格式化的百分比
   */
  private percentage(part: number, total: number): string {
    if (total === 0) return '0.0';
    return ((part / total) * 100).toFixed(1);
  }
  
  /**
   * 将分类结果转换为模块树结构
   * @param translations 翻译数组
   * @returns 模块树结构
   */
  public transformToModules(translations: Translation[] | TranslationInfo[]): {
    moduleTree: TranslationModule;
    referenceStatistics: {
      totalReferences: number;
      keyWithMostReferences: string;
      maxReferenceCount: number;
    };
    transformStatistics: {
      totalModules: number;
      totalKeys: number;
      maxDepth: number;
    };
  } {
    // 先进行基础分类
    const classificationResult = this.classify(translations);
    
    // 转换为模块树
    const transformResult = this.moduleTransformer.transform(classificationResult);
    
    // 处理引用关系
    const referenceResult = this.referenceHandler.processReferences(transformResult.rootModule);
    
    return {
      moduleTree: referenceResult.rootModule,
      referenceStatistics: referenceResult.statistics,
      transformStatistics: transformResult.statistics
    };
  }
  
  /**
   * 生成完整的模块化报告
   * @param translations 翻译数组
   * @returns 报告内容
   */
  public generateModuleReport(translations: Translation[] | TranslationInfo[]): string {
    // 转换为模块树
    const result = this.transformToModules(translations);
    
    // 基础分类报告
    const classificationReport = this.generateReport(this.classify(translations));
    
    // 模块树统计报告
    let moduleReport = '==== ForexDana模块树报告 ====\n\n';
    
    moduleReport += `总模块数: ${result.transformStatistics.totalModules}\n`;
    moduleReport += `总翻译键数: ${result.transformStatistics.totalKeys}\n`;
    moduleReport += `最大模块深度: ${result.transformStatistics.maxDepth}\n\n`;
    
    // 引用统计
    moduleReport += '=== 引用统计 ===\n';
    moduleReport += `总引用数: ${result.referenceStatistics.totalReferences}\n`;
    moduleReport += `引用最多的键: ${result.referenceStatistics.keyWithMostReferences}\n`;
    moduleReport += `最大引用次数: ${result.referenceStatistics.maxReferenceCount}\n\n`;
    
    // 合并报告
    return classificationReport + '\n\n' + moduleReport;
  }
} 